<template>
  <div class="login">
    <!-- 背景视频 -->
    <video
      data-v-cc6c3120=""
      muted="muted"
      src="http://www.chst.vip:8081/crm/media/bg-video.d2d602a9.mp4"
      loop="loop"
      autoplay="autoplay"
      class="video"
    ></video>
    <img
      src="http://www.chst.vip:8081/crm/img/bg2.fc58c850.png"
      alt=""
      class="image"
    />
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm from"
    >
      <h1>管理系统</h1>
      <i
        @click="isErWeiLogin = !isErWeiLogin"
        :class="[
          'min-pic',
          'iconfont',
          isErWeiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <div class="common-login" v-if="!isErWeiLogin">
        <el-form-item label="用户名" prop="username" class="ipt-title">
          <el-input
            class="ipt"
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="ipt-title">
          <el-input
            class="ipt"
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" class="ipt-title">
          <el-input
            v-model="loginForm.captcha"
            class="ipt-cap"
            ref="captcha"
            @keydown.native.enter="submitForm('loginForm')"
          ></el-input>
          <span class="loginCode" @click="getCaptchas" v-html="loginSvg"></span>
          <!-- <el-input v-model.number="loginForm.captcha" class="ipt-cap"></el-input>    -->
        </el-form-item>
        <el-form-item>
          <el-button class="btn" type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </div>
      <!-- 切换二维码登入 -->
      <div class="erwei" v-else>
        <div class="erwei-img">
          <img :src="qrdataurl" alt="" />
          <i class="iconfont icon-saomachenggong mask" v-show="issuccess"></i>
        </div>
        <p>请使用手机微信扫码登入</p>
      </div>
    </el-form>
  </div>
</template>
<script>
import * as api from "../../api/index";
import { mapMutations } from "vuex";
import io from "socket.io-client";
import qrcode from "qrcode";
export default {
  data() {
    var validateCaptcha = (rule, value, callback) => {
      //value表单中的输入值
      //rule验证对象
      //callback只要传参了，表示表单验证不通过，不传参表示表单验证通过
      if (value.length !== 5) {
        callback("验证码必须是5位");
      } else {
        callback();
      }
    };
    var validateUsername = (rule, value, callback) => {
      var reg = /^\w{2,6}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback("用户名可以是数字字母下划线，2到6位");
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value.length < 3) {
        callback("密码不能小于3位");
      } else {
        callback();
      }
    };
    return {
      loginSvg: "",
      issuccess: false,
      qrdataurl: "",
      isErWeiLogin: false,
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        //失去焦点触发
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getCaptchas();
  },
  methods: {
    ...mapMutations(["SET_USER_INFO"]),
    //获取验证码的方法
    getCaptchas() {
      api.getCaptcha().then((res) => {
        this.loginSvg = res.data.img;
      });
    },
    //成功弹出框
    success() {
      this.$message.success("登录成功，正在跳转");
    },
    //失败弹出框
    error(msg) {
      this.$message.error(msg);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        //校验验证码
        api.verifyCaptcha(this.loginForm.captcha.toLowerCase()).then((res) => {
          if (res.data.state) {
            //验证通过，验证账号密码
            api.logins(this.loginForm.username, this.loginForm.password)
              .then((res) => {
                if (res.data.state) {
                  this.success();
                  localStorage.setItem("crm-token", res.data.token);
                  localStorage.setItem( "crm-userInfo",JSON.stringify(res.data.userInfo));
                  localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))//按钮权限
                  this.SET_USER_INFO(res.data.userInfo);
                  this.$router.push("/"); //跳转到主页
                } else {
                  this.error("用户名或密码错误");
                }
              });
          } else {
            this.error("验证码错误");
            this.loginForm.captcha='';//清空输入框的错误验证码
            api.refreshCaptcha().then(res=>{
              this.loginSvg = res.data.img;
            });
            this.$refs.captcha.focus();//让输入框获取焦点
          }
        });
      });
    },
  },
  watch: {
    isErWeiLogin(newVal, oldVal) {
      if (newVal) {
        //二维码登录
        //通过socket.io建立连接
        let socket = io("wss://chst.vip");
        //监听socket连接成功事件,请求获取二维码地址
        socket.on("connectSuccess", (res) => {
          // console.log(res.sid);
          let erweiSid = res.sid;
          // console.log(erweiSid);
          api.erweiUrl(erweiSid).then((res) => {
            // console.log(res);
            //通过qrcode生成二维码
            let qrurl = res.data.scanCodeUrl;
            qrcode.toDataURL(qrurl, (err, dataurl) => {
              // console.log(dataurl);
              this.qrdataurl = dataurl;
            });
          });
        });
        socket.on("scancodeSuccess",(data)=>{
          // console.log(data);
          let wcode = data.wechatCode
          // console.log(wcode);
          if(data.state){
            this.issuccess = true
            api.erwei(wcode)
            .then(res=>{
              if(res.data.state){
                // console.log(res);
                this.success();
                localStorage.setItem("crm-token", res.data.token);
                localStorage.setItem( "crm-userInfo",JSON.stringify(res.data.userInfo));
                localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))//按钮权限
                this.SET_USER_INFO(res.data.userInfo);
                this.$router.push("/"); //跳转到主页
              }else{
                this.$message.error('微信登录失败')
              }
            })
          }else{
            this.$message.error('扫码失败')
          }
        })
      }else{
        this.issuccess=false
      }
    },
  },
};
</script>
<style>
.login {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.video {
  position: fixed;
  z-index: 1;
}
.image {
  position: fixed;
  left: 320px;
  top: 260px;
  z-index: 50;
  width: 340px;
  height: 340px;
  opacity: .5;
}
.from {
  width: 400px;
  height: 520px;
  position: fixed;
  z-index: 99;
  right: 10%;
  top: 25%;
  background: rgba(0, 0, 0, 0.3);
  border: rgba(0, 0, 0, 0.3);
  border-radius: 5%;
}
.from h1 {
  text-align: center;
  color: #fff;
  padding: 100px 0 50px;
}
.min-pic {
  font-size: 60px;
  color: #fff;
  position: absolute;
  right: -1px;
  top: -1px;
  cursor: pointer;
  opacity: 0.7;
}
.ipt {
  width: 240px;
}
.ipt-cap {
  width: 120px;
  border: 0 !important;
  display: inline-block;
}
.loginCode {
  display: inline-block;
  width: 120px;
  height: 40px;
  background: #fff;
  vertical-align: top;
  border-radius: 0 5px 5px 0;
  margin-top: 1px;
  cursor: pointer;
}
.loginCode svg {
  width: 118px !important;
  height: 38px;
}
.el-input__inner {
  height: 40px;
  border-right: none;
  border-radius: 5px 0 0 5px;
}
.ipt-title .el-form-item__label {
  color: #fff !important;
}
.btn {
  color: #fff;
  width: 240px;
  background: linear-gradient(to right, #1495fb, #0031fe);
}
.erwei {
  width: 400px;
  height: 240px;
  text-align: center;
}
.erwei-img,
img {
  width: 200px;
  height: 200px;
  display: inline-block;
  position: relative;
}
.mask{
  font-size: 200px;
  background: rgba(241, 239, 239, 0.685);
  position: absolute;
  top: 0;
  left: 0;
  color: green;
}
</style>